// 运行时配置

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
import { RunTimeLayoutConfig } from '@@/plugin-layout/types';

import { fetchDataMenuList } from '@/services/sys/MenuService';

import Footer from '@/components/Footer';
import RightContent from '@/components/RightContent';
import { findBySettingInfo } from '@/services/sys/sys_config';
import useUserStore from '@/stores/userStore';
import type { ProSettings } from '@ant-design/pro-layout/es/defaultSettings';
import { useLocation, useNavigate } from '@umijs/max';
import { useRequest } from 'ahooks';
import React, { useEffect, useRef } from 'react';

export async function getInitialState(): Promise<{
  userInfo: API.LoginUser;
  navList: object | string | number;
  name: string;
  settings?: Partial<ProSettings>;
}> {
  let useUserStore1 = new useUserStore();
  let userInfo = useUserStore1.getUserInfo();

  let result = await fetchDataMenuList();
  console.log(result);
  // eslint-disable-next-line react-hooks/rules-of-hooks
  // useRoutes(result.data)
  //useRoutes()

  //console.log(routes)
  return { name: userInfo.username, userInfo: userInfo, navList: result };
}

// @ts-ignore
export const layout: RunTimeLayoutConfig = ({
  initialState,
  setInitialState,
}) => {
  const location = useLocation();
  const navigate = useNavigate();
  const keepElements = useRef<{ [key: string]: React.ReactNode }>({});
  let cacheKey = 'settingInfo';
  const { data: settingInfo, run: fetchBySettingInfo } = useRequest(
    findBySettingInfo,
    {
      cacheKey: cacheKey,
      refreshOnWindowFocus: false,
      cacheTime: 0,
      onSuccess: (res) => {
        setInitialState({
          ...initialState,

          title: res?.title,
          primaryColor: res?.color,
          logoUrl: res?.logoUrl,
        });
      },
      setCache: (data) => localStorage.setItem(cacheKey, JSON.stringify(data)),
      getCache: () => JSON.parse(localStorage.getItem(cacheKey) || '{}'),
    },
  );
  useEffect(() => {
    fetchBySettingInfo();
  }, [initialState?.name]);

  return {
    //   name: initialState?.name,
    logo: settingInfo?.logoUrl,
    name: 'Serati Ma',
    avatar:
      'https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqdXe4Ne7Gicp0gMxakdsA5sKhjS2DArficBA3icGZQmzaZXCGuxj3ukMiat9W7Wm4xUHsKENhTH2tkYQ/132',
    iconfontUrl: '//at.alicdn.com/t/c/font_3624205_r2620klwtf.js',
    /*    routers: [
          {
            path: '/',
            component: '@/layouts/BasicLayout',
            routes: [
              { path: '/', redirect: '/dashboard' },
              {
                path: '/dashboard',
                name: 'Dashboard',
                component: '@/pages/Dashboard',
              },
              // 更多路由...
            ],
          },
          // 更多路由配置...
        ],*/
    /* menuDataRender: () => {
       return initialState?.navList;
     },*/
    menu: {
      locale: false,
      params: initialState,

      request: () => {
        return new Promise((resolve, reject) => {
          fetchDataMenuList()
            .then((res) => {
              console.log(res);
              resolve(res);
            })
            .catch((err) => {
              reject(err);
            });
        });
      },
    },
    key: 'userInfo',
    breadcrumbRender: (routers = []) => [
      {
        path: '/',
        breadcrumbName: '主页',
      },
      ...routers,
    ],

    rightContentRender: () => <RightContent />,
    title: settingInfo?.title,
    // hasCustomTabs: true, // 启用自定义标签页布局
    locale: true,
    layout: 'mix',
    siderWidth: 208,
    navTheme: 'dark',
    theme: 'dark',
    headerHeight: 48,
    primaryColor: settingInfo?.color,
    contentWidth: 'Fluid',

    token: {
      colorPrimary: settingInfo?.color,
    },
    footerRender: () => <Footer />,
  };
};
